﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Globalization;
using System.Linq;
using EstateNuke.Data.Properties;

namespace EstateNuke.Data
{
    public partial class Room
    {
        #region Fileds & Properties

        /// <summary>
        /// </summary>
        public string DisplayName
        {
            get
            {
                if (!EntranceReference.IsLoaded)
                {
                    EntranceReference.Load(MergeOption.PreserveChanges);
                }
                return string.Format("{0}-{1}{2}", Entrance.DisplayName, Name, IsDeleted ? " (已删除)" : "");
            }
        }

        /// <summary>
        /// </summary>
        public SmallOrder ActiveSmallOrder
        {
            get
            {
                if (!ActiveAgreementReference.IsLoaded)
                {
                    ActiveAgreementReference.Load(MergeOption.PreserveChanges);
                }
                return ActiveAgreement != null ? ActiveAgreement.SmallOrder : null;
            }
        }

        /// <summary>
        /// </summary>
        public LargeOrder ActiveLargeOrder
        {
            get
            {
                if (!ActiveAgreementReference.IsLoaded)
                {
                    ActiveAgreementReference.Load(MergeOption.PreserveChanges);
                }
                return ActiveAgreement != null ? ActiveAgreement.LargeOrder : null;
            }
        }

        /// <summary>
        /// </summary>
        public Contract ActiveContract
        {
            get
            {
                if (!ActiveAgreementReference.IsLoaded)
                {
                    ActiveAgreementReference.Load(MergeOption.PreserveChanges);
                }
                return ActiveAgreement != null ? ActiveAgreement.Contract : null;
            }
        }

        /// <summary>
        /// </summary>
        public Cancellation ActiveCancellation
        {
            get
            {
                if (!ActiveAgreementReference.IsLoaded)
                {
                    ActiveAgreementReference.Load(MergeOption.PreserveChanges);
                }
                return ActiveAgreement != null ? ActiveAgreement.Cancellation : null;
            }
        }

        /// <summary>
        /// </summary>
        public IList<RoomPicture> RoomPictures
        {
            get
            {
                return InternalRoomPictures.Where(roomPicture => roomPicture.IsDeleted == false).ToList();
            }
        }

        /// <summary>
        /// </summary>
        public IList<Agreement> Agreements
        {
            get
            {
                return InternalAgreements.Where(agreement => agreement.IsDeleted == false).ToList();
            }
        }

        #endregion

        #region Set RoomState

        /// <summary>
        /// </summary>
        public void SetRoomStateSellable(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            RoomStateId = 1;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
        }

        /// <summary>
        /// </summary>
        public void SetRoomStateReserved(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            RoomStateId = 2;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
        }

        /// <summary>
        /// </summary>
        public void SetRoomStateSmallOrdered(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            RoomStateId = 3;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
        }

        /// <summary>
        /// </summary>
        public void SetRoomStateLargeOrdered(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            RoomStateId = 4;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
        }

        /// <summary>
        /// </summary>
        public void SetRoomStateContracted(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            RoomStateId = 5;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
        }

        /// <summary>
        /// </summary>
        public void SetRoomStateRecorded(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            RoomStateId = 6;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
        }

        #endregion

        #region Add & Remove RoomPicture

        /// <summary>
        /// </summary>
        /// <returns></returns>
        public RoomPicture AddRoomPicture(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            var roomPicture = new RoomPicture
                                  {
                                      RowId = Guid.NewGuid(),
                                      CreatedDate = DateTime.Now,
                                  };
            InternalRoomPictures.Add(roomPicture);
            roomPicture.IsDeleted = false;
            roomPicture.ModifiedDate = DateTime.Now;
            roomPicture.ModifiedByUser = modifiedUser;
            return roomPicture;
        }

        /// <summary>
        /// </summary>
        /// <param name = "roomPicture"></param>
        /// <param name = "modifiedUser"></param>
        public void RemoveRoomPicture(RoomPicture roomPicture, User modifiedUser)
        {
            if (roomPicture == null)
            {
                throw new ArgumentNullException("roomPicture");
            }
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalRoomPictures.Contains(roomPicture))
            {
                roomPicture.Delete(modifiedUser);
            }
        }

        #endregion

        #region Add & Remove Agreement

        /// <summary>
        /// </summary>
        /// <returns></returns>
        internal Agreement AddAgreement(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            var agreement = new Agreement
                                {
                                    RowId = Guid.NewGuid(),
                                    CreatedDate = DateTime.Now,
                                };
            InternalAgreements.Add(agreement);
            agreement.IsDeleted = false;
            agreement.ModifiedDate = DateTime.Now;
            agreement.ModifiedByUser = modifiedUser;
            agreement.SerialNumber = string.Format("SN{0}", DateTime.Now.ToString("yyyyMMddHHmmss"));
            agreement.AgreementStateId = 0;
            return agreement;
        }

        /// <summary>
        /// </summary>
        /// <param name = "agreement"></param>
        /// <param name = "modifiedUser"></param>
        internal void RemoveAgreement(Agreement agreement, User modifiedUser)
        {
            if (agreement == null)
            {
                throw new ArgumentNullException("agreement");
            }
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (InternalAgreements.Contains(agreement))
            {
                agreement.Delete(modifiedUser);
            }
        }

        #endregion

        #region Create Active SmallOrder

        /// <summary>
        /// </summary>
        /// <returns></returns>
        public SmallOrder CreateActiveSmallOrder(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (RoomStateId != 1)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotCreateSmallOrder, "房间不是可售状态"));
            }
            if (!ActiveAgreementReference.IsLoaded)
            {
                ActiveAgreementReference.Load(MergeOption.PreserveChanges);
            }
            if (ActiveAgreement != null && ActiveAgreement.AgreementStateId >= 1)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotCreateSmallOrder, "当前协议不是未售状态"));
            }
            if (ActiveAgreement == null)
            {
                ActiveAgreement = AddAgreement(modifiedUser);
            }
            return ActiveAgreement.CreateSmallOrder(modifiedUser);
        }

        #endregion

        #region Create Active LargeOrder

        /// <summary>
        /// </summary>
        /// <returns></returns>
        public LargeOrder CreateActiveLargeOrder(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (RoomStateId != 1 && RoomStateId != 3)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotCreateLargeOrder, "房间不是可售或小定状态"));
            }
            if (!ActiveAgreementReference.IsLoaded)
            {
                ActiveAgreementReference.Load(MergeOption.PreserveChanges);
            }
            if (ActiveAgreement != null && ActiveAgreement.AgreementStateId >= 2)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotCreateLargeOrder, "当前协议不是未售或小定状态"));
            }
            if (ActiveAgreement == null)
            {
                ActiveAgreement = AddAgreement(modifiedUser);
            }
            return ActiveAgreement.CreateLargeOrder(modifiedUser);
        }

        #endregion

        #region Create Active Contract

        /// <summary>
        /// </summary>
        /// <returns></returns>
        public Contract CreateActiveContract(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (RoomStateId != 1 && RoomStateId != 3 && RoomStateId != 4)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotCreateContract, "房间不是可售、小定或大定状态"));
            }
            if (!ActiveAgreementReference.IsLoaded)
            {
                ActiveAgreementReference.Load(MergeOption.PreserveChanges);
            }
            if (ActiveAgreement != null && ActiveAgreement.AgreementStateId >= 4)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotCreateContract, "当前协议不是未售、小定或大定状态"));
            }
            if (ActiveAgreement == null)
            {
                ActiveAgreement = AddAgreement(modifiedUser);
            }
            return ActiveAgreement.CreateContract(modifiedUser);
        }

        #endregion

        #region Create Active Cancellation

        /// <summary>
        /// </summary>
        /// <returns></returns>
        public Cancellation CreateActiveCancellation(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            if (RoomStateId != 1 && RoomStateId != 3 && RoomStateId != 4 && RoomStateId != 5)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotCreateCancellation, "房间不是可售、小定、大定或已签状态"));
            }
            if (!ActiveAgreementReference.IsLoaded)
            {
                ActiveAgreementReference.Load(MergeOption.PreserveChanges);
            }
            if (ActiveAgreement != null && ActiveAgreement.AgreementStateId >= 8)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.CannotCreateCancellation, "当前协议不是未售、小定、大定或已签状态"));
            }
            if (ActiveAgreement == null)
            {
                ActiveAgreement = AddAgreement(modifiedUser);
            }
            return ActiveAgreement.CreateCancellation(modifiedUser);
        }

        #endregion

        #region Ensure

        /// <summary>
        /// </summary>
        public void Ensure()
        {
            if (string.IsNullOrEmpty(Name))
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture, Resources.NotNullAllowed, RowId, "Room", "Name"));
            }
            if (SaleArea < 0)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture, Resources.NonNegativeNumberAllowed, RowId, "Room", "SaleArea"));
            }
            if (UnitPrice < 0)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture, Resources.NonNegativeNumberAllowed, RowId, "Room", "UnitPrice"));
            }
            if (TotalPrice < 0)
            {
                throw new EntityException(string.Format(CultureInfo.CurrentCulture, Resources.NonNegativeNumberAllowed, RowId, "Room", "TotalPrice"));
            }
            Name = Name.Length > 64 ? Name.Substring(0, 64) : Name;
            Description = string.IsNullOrEmpty(Description) ? null : Description.Length > 512 ? Description.Substring(0, 512) : Description;
        }

        #endregion

        #region Delete

        /// <summary>
        /// </summary>
        public void Delete(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            IsDeleted = true;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
            ((List<RoomPicture>) RoomPictures).ForEach(roomPicture => roomPicture.Delete(modifiedUser));
            ((List<Agreement>) Agreements).ForEach(agreement => agreement.Delete(modifiedUser));
        }

        /// <summary>
        /// </summary>
        public void CancelDelete(User modifiedUser)
        {
            if (modifiedUser == null)
            {
                throw new ArgumentNullException("modifiedUser");
            }
            IsDeleted = false;
            ModifiedDate = DateTime.Now;
            ModifiedByUser = modifiedUser;
        }

        #endregion
    }
}